#!/bin/bash

# 此脚本需要在所有部署监控脚本的节点执行，用于应用检测监控脚本是否处于运行中，支持同时传入多个参数, 多个参数使用空格隔开

# 系统ID
system_id=$(cat config.cnf | grep SystemId | awk -F "=" '{print $2}')
# 告警存放文件夹
alert_dir=$(cat config.cnf | grep AlertDir | awk -F "=" '{print $2}')
# 告警缓存文件
alarm_file_tmp="script_check_alarm.txt"
echo -n "" >${alarm_file_tmp}
# 本机ip
local_ip=$(ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")

execute_cycle=$(cat config.cnf | grep ExecuteCycle | awk -F "=" '{print $2}')
scripts=$@

# 应用监控脚本进程状态监控
script_pro_check() {
	for i in $scripts; do 
		script_pro=$(ps -elf | grep $i | grep -v grep | grep -v monitor_script_check.sh | wc -l)
		if [[ ${script_pro} == 0 ]]; then
			# 进程状态不存在，告警
			./gen_alarm.sh -g "服务状态" "${i}监控脚本运行状态异常,${i}监控脚本进程不存在,IP:$(hostname -I)" 3 "监控服务状态" "script_pro" ${alarm_file_tmp}
		else
			# 告警存在，恢复原告警
			./gen_alarm.sh -r "服务状态" "${i}监控脚本进程恢复正常,IP:$(hostname -I)" "监控服务状态" "script_pro" ${alarm_file_tmp}
		fi
	done
}

while true; do
    holidays_date=$(cat config.cnf | grep Holidays | awk -F "=" '{print $2}' | sed "s/,/ /g")
	current_date=$(date +'%Y-%m-%d')
	echo $holidays_date | grep -o $current_date >> /dev/null
	if [[ $? -eq 0 ]]; then
		exit 0
	else
		echo -n "" >${alarm_file_tmp}
		script_pro_check
		# 将缓存告警放入告警文件夹
		./gen_alarm.sh -s ${alarm_file_tmp}
		sleep ${execute_cycle}
	fi
done